local md5 = require "md5"

--md5加密用的
local salt = "Jianmao"

-------------------------------------------------------------------------------
---! 对外接口
---! 数据库操作方法
-------------------------------------------------------------------------------
FILE_D = {}

---! 添加salt后,返回md5
function FILE_D:salt_md5(str)
    return md5.sumhexa(str .. salt)
end

---! 直接返回context
function FILE_D:read_common_context(method, ...)
    local ok, reply = FILE_D:read_common_data(method, ...)
    if not ok then
        return false
    end
    if #reply > 0 and #(reply[1]) > 0 then
        local checksum = self:salt_md5(reply[1])
        if checksum ~= reply[2] then
            local path,name,_,_ =  ...
            spdlog.error("FILE_D", string.format("read_common_context method:%s path:%s name:%s checksum error, old:%s now:%s",method,path,name, reply[2], checksum))
            return false
        end
        return true,reply[1]
    end
    return false
end

---! 保存带checksum的数据
function FILE_D:write_common_context(method, ...)
    --需要4个参数
    --local params = table.pack(...)
    if 4 ~= select("#", ...) then
        spdlog.error("FILE_D", "write_common_context error, args num ~=5 ")
        return false
    end

    local args = {...}
    local _,_,_,context = ...
    local checksum = self:salt_md5(context)
    table.insert(args,checksum)
    return FILE_D:write_common_data(method, table.unpack(args))
end

function FILE_D:read_common_data(method, ...)
    local rpc = {}
    rpc.method = method .. ".load"
    rpc.data = table.pack(...)
    local ok, reply = THREAD_D:send("database", rpc)
    if not ok then
        return false
    end
    return true, reply
end

function FILE_D:update_common_data(method, ...)
    local rpc = {}
    rpc.method = method .. ".update"
    rpc.data = table.pack(...)
    local ok, reply = THREAD_D:send("database", rpc)
    if not ok then
        return false
    end
    return true, reply
end

function FILE_D:write_common_data(method, ...)
    local rpc = {}
    rpc.method = method .. ".save"
    rpc.data = table.pack(...)
    local ok, reply = THREAD_D:send("database", rpc)
    if not ok then
        return false
    end
    return true, reply
end
